package com.woniuxy.main.realm;

import com.woniuxy.main.pojo.Staff;
import com.woniuxy.main.service.StaffService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/*
 *
 *  @author zhc
 *  @create 2019-08-05 10:06
 */

public class StaffRealm extends AuthorizingRealm {

    @Resource
    private StaffService staffService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("正在从数据库查询当前用户的角色/权限");
        //模拟从数据库中查询出当前用户的角色
        //得到账号
        String account = (String)principals.getPrimaryPrincipal();

        //用于存放从数据库中查询出当前用户有哪些角色
        Set<String>roles = new HashSet<>();
        roles.add("s");//假设查询出是admin
        //roles.add("teacher");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);

        return null;
    }
    //认证的方法：从数据库中查询当前用户的信息（账号、密码等）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("正在进行认证");
        //如果该方法的返回值为null，代表没有在数据库中查询到该账户
        //获取用户提交的账号
        String saccount = (String)token.getPrincipal();
        System.out.println(saccount);
        //获取密码
        String pass = new String((char[])token.getCredentials());
        String s = new SimpleHash("MD5", pass,saccount,1024).toString();
        System.out.println(s);
        //假设通过账号从数据库中查询出数据
        Staff resultUser = staffService.selectStaffBySaccount(saccount);
//
        if (resultUser==null) {
            //账号不存在
            return null;
        }
        //获取盐值
        ByteSource salt = ByteSource.Util.bytes(resultUser.getSaccount());
        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(
                        resultUser.getSaccount(),
                        resultUser.getSpassword(),
                        salt,
                        getName());

        return info;
    }
}
